import {urls} from '../config';
import listener from "../utils/listener";
import http from "../utils/http";
import Validate from "../utils/validate";

listener.once('app.init', (options) => {
	const {app} = options;

	//todo 请求发起前的处理，可以给每次请求附加session
	http.onRequest = (config) => {
		config.data = config.data || {};

		//提交前的验证支持
		if (config.validate instanceof Validate) {
			if (!config.validate.check(config.data)) {
				wx.showToast({title: config.validate.getError(), icon: 'none'});
				return false;
			}
		}

		//请求附加session
		if (app.globalData.session_key) {
			app.globalData.session_key = wx.getStorageSync('session');
		}
		const session = app.globalData.session_key;
		if (session) {
			config.data.session = session;
		} else {
			//直接取消请求，放入登录回调中
			http.onLogin(config);
			return false;
		}

		return config;
	};

	//todo 检查服务器业务是否成功
	http.onCheckResponse = (response) => {
		const data = response.data;
		//如果返回1，则表明服务器业务正常，将会走http.onResponseData回调函数
		if (data.code === 1) return 1;
		//如果返回-1，则表明本次请求失效
		else if (data.code === -1) return -1;
		//如果返回0，则表明服务器业务失败
		return 0;
	};

	//todo 服务器返回数据处理
	http.onResponseData = (data) => {
		return data.data;
	};


	//登录失效的回调器
	const loginInvalidOptions = [],
		cleanLoginInvalidOptions = () => loginInvalidOptions.splice(0, loginInvalidOptions.length),
		execLoginInvalidOptions = () => loginInvalidOptions.forEach(http);

	//显示登录失败提示
	const showLoginFailMsg = () => wx.showModal({content: '网络出现故障，请稍后再试~', showCancel: false});

	//是否正在登录中
	let isLoginLoading = false;

	//todo 如果一个请求两次出现登录失效，应检查服务器端是否出现异常
	http.onLoginInvalidTip = showLoginFailMsg;

	// todo 登录服务器
	http.onLogin = (options) => {
		//把登录失效的接口回调器缓存起来
		loginInvalidOptions.push(options);

		//如果已经又一个登录实例在进行中，则直接返回
		if (isLoginLoading) return;

		isLoginLoading = true;
		wx.login({
			success: (res) => {
				wx.request({
					url: urls.member.login,
					data: {
						code: res.code
					},
					success: (res) => {
						res = res.data;
						if (res.code) {
							//todo 登录成功，缓存session_key
							app.globalData.session_key = res.data.session_key;
							wx.setStorageSync('session', res.data.session_key);
							execLoginInvalidOptions();
						} else {
							console.error('request.success.error', res.msg);
							showLoginFailMsg();
						}
					},
					fail: (err) => {
						console.error('request.fail', err);
						showLoginFailMsg();
					},
					complete: () => {
						isLoginLoading = false;
						cleanLoginInvalidOptions();
					}
				});
			},
			fail: (err) => {
				//打印出来，方便排查
				console.error('wx.login', err);
				isLoginLoading = false;
				cleanLoginInvalidOptions();
				showLoginFailMsg();
			}
		});
	}
});
